package com.supplychain.scm.core.rocketmq.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.supplychain.scm.core.basis.constant.StringPool;
import com.supplychain.scm.core.rocketmq.constant.RocketMqConstant;
import lombok.experimental.UtilityClass;

import java.util.Map;
import java.util.Optional;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName RocketThreadLocalUtils
 * @Description  Consumer ThreadLocal
 * @createTime 11:14:00 2023/03/14
 */
@UtilityClass
public class RocketThreadLocalUtils {

    private final ThreadLocal<Map<String, String>> ROCKET_THREAD_LOCAL = new TransmittableThreadLocal<>();

    public Map<String, String> getMessageHead() {
        return ROCKET_THREAD_LOCAL.get();
    }

    public void setMessageHead(Map<String, String> headMessage) {
        ROCKET_THREAD_LOCAL.set(headMessage);
    }

    public void remove(){
        ROCKET_THREAD_LOCAL.remove();
    }

    /**
     * 业务消息唯一key
     * @return
     */
    public String getUniqueKey() {
        return Optional.ofNullable(getMessageHead()).map((head) -> head.get(RocketMqConstant.KEYS)).orElse(StringPool.EMPTY);
    }

    /**
     * 消息链路Id
     * @return
     */
    public String getMessageLinkId() {
        return Optional.ofNullable(getMessageHead()).map((head) -> head.get(RocketMqConstant.MESSAGE_LINK_ID)).orElse(StringPool.EMPTY);
    }

    /**
     * 消息来源
     * @return
     */
    public String getMessageOrigin() {
        return Optional.ofNullable(getMessageHead()).map((head) -> head.get(RocketMqConstant.MESSAGE_ORIGIN)).orElse(StringPool.EMPTY);
    }
}
